<?php
/**
 * Auther: Joshua Conero
 * Date: 2017/12/7 0007 22:05
 * Email: brximl@163.com
 * Name: 项目渲染中间件
 */

namespace App\Cythina;


class Render
{
    const JsKey = 'a__script';
    protected $data = array();  // 渲染值

    /**
     * Render constructor.
     * @param null|array $data
     */
    public function __construct($data=null)
    {
        if(is_array($data)){
            $this->data = $data;
        }
    }

    /**
     * js 脚本设置
     * @param string|array $key
     * @param null $value
     * @return $this
     */
    public function JsVar($key, $value=null){
        $jskey = self::JsKey;
        if(!isset($this->data[$jskey])){
            $this->data[$jskey] = array();
        }
        if(is_array($key)){
            $this->data[$jskey] = array_merge($this->data['a__script'], $key);
        }else if($value && $key){
            $this->data[$jskey][$key] = $value;
        }
        return $this;
    }

    /**
     * 设置标题
     * @param $title
     * @return $this
     */
    function title($title){
        $this->data['a__tpl'] = $this->data['a__tpl'] ?? [];
        $this->data['a__tpl']['title'] = $title;
        return $this;
    }
    /**
     * @param string|array $key
     * @param mixed $value
     * @return $this
     */
    public function set($key, $value=null){
        if(is_array($key)){
            $this->data = array_merge($this->data, $key);
        }elseif ($key && $value){
            $this->data[$key] = $value;
        }
        return $this;
    }

    /**
     * @param $name
     * @param $value
     */
    public function __set($name, $value)
    {
        $this->set($name, $value);
    }

    /**
     * @return array
     */
    public function toArray(){
        $data = $this->data;
        // js 脚本处理
        $jskey = self::JsKey;
        if(isset($data[$jskey])){
            $data[$jskey] = is_array($data[$jskey])? json_encode($data[$jskey]): $data[$jskey];
        }

        return $data;
    }
}